Skip to content

Latest commit

 

History

History
62 lines (56 loc) · 1.89 KB

File metadata and controls

62 lines (56 loc) · 1.89 KB

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9 Output: [1, 2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 

Solutions (Rust)

1. Binary Search

implSolution{pubfntwo_sum(numbers:Vec<i32>,target:i32) -> Vec<i32>{let len = numbers.len();for i in0..len {let tg = target - numbers[i];letmut left = i + 1;letmut right = len - 1;letmut mid = (left + right) / 2;while left <= right {if numbers[mid] == tg {returnvec![i asi32 + 1, mid asi32 + 1];}elseif numbers[mid] < tg { left = mid + 1; mid = (left + right) / 2;}else{ right = mid - 1; mid = (left + right) / 2;}}}Vec::new()}}

2. Two Pointers

implSolution{pubfntwo_sum(numbers:Vec<i32>,target:i32) -> Vec<i32>{letmut i = 0;letmut j = numbers.len() - 1;while numbers[i] + numbers[j] != target {if numbers[i] + numbers[j] < target { i += 1;}else{ j -= 1;}}vec![i asi32 + 1, j asi32 + 1]}}
close